package com.yt.app.api.action;

import com.google.common.base.Joiner;
import com.yt.app.api.action.base.BaseAction;
import com.yt.app.api.vo.BaseVo;
import com.yt.app.core.interfaces.AppTopicFavService;
import com.yt.app.core.interfaces.AppTopicService;
import com.yt.app.core.model.AppTopic;
import com.yt.app.core.model.AppTopicFav;
import com.yt.core.MsgBean;
import com.yt.core.dao.filter.DynamicSQLFilterImpl;
import com.yt.core.dao.filter.QueryFilter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@Api(tags = "07.个人中心")
@RequestMapping("/my")
public class MyController extends BaseAction{
    @Autowired
    private AppTopicFavService topicFavService;
    @Autowired
    private AppTopicService topicService;

    @ApiOperation(value="我的收藏", httpMethod = "GET")
    @RequestMapping("/fav/myFav")
    public @ResponseBody  Object updatePassword(
            @ApiParam("上一页最后一个记录的ID") @RequestParam(value = "lastId", required = false, defaultValue = "0") Long lastId,
            @ApiIgnore HttpServletRequest request
    ){
        MsgBean msgBean = new MsgBean();
        Long uid = BaseVo.getUIDFromHeader(request);
        QueryFilter filter = new DynamicSQLFilterImpl();
        filter.addFilter("Q_uid_L_EQ", String.valueOf(uid));
        filter.setSortField("id", true);
        if(lastId > 0){
            filter.addFilter("Q_id_L_LT", String.valueOf(lastId));
        }

        List<AppTopicFav> favList = topicFavService.find(filter);
        if(favList != null && !favList.isEmpty()) {
            List<Long> favIdList = new ArrayList<Long>(favList.size());
            List<AppTopic> topicList = new ArrayList<AppTopic>(favList.size());
            for(AppTopicFav fav : favList){
                favIdList.add(fav.getTopicId());
            }
            String topicIds = Joiner.on(",").join(favIdList).toString();
            QueryFilter topicFilter = new DynamicSQLFilterImpl();
            topicFilter.addFilter("Q_id_S_IN", topicIds);
            topicList = topicService.find(topicFilter);
            msgBean.put("topics", topicList);
            msgBean.put("lastId", favIdList.get(favIdList.size() -1));
        }else{
            msgBean.put("lastId", -1);
            msgBean.put("topics", new ArrayList<AppTopic>());
        }

        return msgBean.returnMsg();
    }

}
